import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import "./index.scss"
import { checkeAIPayStatus, getAIPriceList, getPayQrCode } from "./api"
import { setPv_new } from "@/utils"

interface IPriceProps {
    price: number
    point: number
    extra?: number
    checked: boolean
    handleChecked(): void
}

const PriceBox = ({ price, point, extra, checked, handleChecked }: IPriceProps) => {
    return <div className="ai_recharge_price" onClick={handleChecked} style={checked ? {
        border: '2px solid #EF3964',
        background: "#FDEBF0"
    } : {}}>
        <div className="point_box">
            <div className="title_text">AI点数</div>
            <div className="point_num_box">
                <div className="point_num">{point}</div>
                {extra != 0 && <div className="extra"><span>加赠+{extra}</span></div>}
            </div>
        </div>
        <div className="price_box">
            <div>￥</div>
            <div>{price}</div>
        </div>
        {checked && <div className="ai_recharge_checked_box">
            <div className="triangle"></div>
            <i className="iconfont icon-duigou"></i>
        </div>}
    </div>
}

interface IProps {
    pointNum: number
    username: string
    avatar: string
    refresh(): void
    onClose: () => void
}

type IStatus = 0 | 1 | 2 // 0 waiting 1 success 2 timeout
interface IPriceItem { vip_type: string; price: number; amount_max_other: number; give_away: number }
const RechargeAiPopup = ({ pointNum, username, avatar, refresh,onClose }: IProps) => {
    const [select, setSelect] = useState<string>('')
    const [price, setPrice] = useState<number>(0)
    const [priceList, setPriceList] = useState<IPriceItem[]>([])
    const [status, setStatus] = useState<IStatus>(0)
    const [qrCode, setQrCode] = useState<string>("")
    const time = useRef<number>(0)
    const timer = useRef<number>(0)
    const timeout = useRef<number>(0)
    const successTimeout = useRef<number>(0)

    const close = useCallback(() => {
        if (timer.current) {
            clearInterval(timer.current)
        }
        if (timeout.current) {
            clearTimeout(timeout.current)
        }
        if (successTimeout.current) {
            clearTimeout(successTimeout.current)
        }
        onClose()
        refresh()
    }, [refresh])

    const check = useCallback(() => {
        checkeAIPayStatus(time.current).then(resultData => {
            if (resultData.stat === 1) {
                setPv_new(7598)
                setStatus(1)
                refresh()
                successTimeout.current = window.setTimeout(() => {
                    close()
                }, 2000);
                if (timer.current) {
                    clearInterval(timer.current)
                }
                if (timeout.current) {
                    clearTimeout(timeout.current)
                }
            }
        });
    }, [close, refresh, time])

    const getQRCode = useCallback((type:string) => {
        if (timer.current) {
            clearInterval(timer.current)
        }
        if (timeout.current) {
            clearTimeout(timeout.current)
        }
        if (successTimeout.current) {
            clearTimeout(successTimeout.current)
        }
        setStatus(0)
        getPayQrCode({ type }).then(res => {
            time.current = Number(new Date()) / 1000
            setQrCode(res.unifyPayQrcode)
            timeout.current = window.setTimeout(() => {
                if (timer.current) {
                    clearInterval(timer.current)
                }
                setStatus(2)
            }, 180 * 1000);
            timer.current = window.setInterval(() => {
                check()
            }, 1000)
        })
    }, [check])

    const handleChecked = useCallback((point: string, price: number) => {
        setSelect(point)
        getQRCode(point)
        setPrice(price)
    }, [getQRCode])

    const getPriceList = useCallback(() => {
        getAIPriceList().then(data => {
            data.json().then(resultData => {
                if (resultData.code == 1) {
                    setPriceList(resultData.data.vip_type)
                    setSelect(resultData.data.vip_type[2].vip_type)
                    getQRCode(resultData.data.vip_type[2].vip_type)
                    setPrice(resultData.data.vip_type[2].price)
                }
            });
        });
    }, [getQRCode])


    useEffect(() => {
        getPriceList()
        return () => {
            if (timer.current) {
                clearInterval(timer.current)
            }
            if (timeout.current) {
                clearTimeout(timeout.current)
            }
            if (successTimeout.current) {
                clearTimeout(successTimeout.current)
            }
        }
    }, [])

    return (
        <div className="recharge_ai_box">
            <div className="recharge_ai_header">
                <div className="recharge_uesr_box">
                    <div className="recharge_user_image" style={{
                        backgroundImage: `url(${avatar})`,
                        backgroundSize: '100% 100%',
                    }}></div>
                    <div className="recharge_user_info">
                        <div className="username">{username}</div>
                        <div className="remain">剩余AI点数: {pointNum}</div>
                    </div>
                </div>
                <div onClick={() => {
                    close()
                }} style={{
                    height: '16px',
                    width: '16px',
                    margin: '11px 13px 0 0',
                    cursor: 'pointer'
                }}>
                    <i className="iconfont icon-cuowu" style={{
                        fontSize: '12px',
                        color: '#333333',
                    }} ></i>
                </div>
            </div>
            <div className="recharge_ai_content">
                <div className="recharge_ai_content_left">
                    <div className="title_box">
                        <div className="title_img"></div>
                        <div className="title">充值AI点数</div>
                    </div>
                    <div className="content_box">
                        <div className="ai_recharge_text_item">
                            <div className="point"></div>
                            <div className="ai_recharge_text">利用AI激发创意，高效 生成高质量文案、图片</div>
                        </div>
                        <div className="ai_recharge_text_item">
                            <div className="point"></div>
                            <div className="ai_recharge_text">开拓多样化的创意，制 作出各种各样风格的文 案和图片</div>
                        </div>
                        <div className="ai_recharge_text_item">
                            <div className="point"></div>
                            <div className="ai_recharge_text">解放双手，给AI指令， 释放您的创意和时间</div>
                        </div>
                    </div>
                </div>
                <div className="recharge_ai_content_right">
                    <div className="recharge_ai_price_box">
                        {priceList.map((item) => <PriceBox
                            key={item.vip_type}
                            price={item.price}
                            point={item.amount_max_other}
                            checked={select === item.vip_type}
                            extra={item.give_away }
                            handleChecked={() => {
                                handleChecked(item.vip_type, item.price)
                            }} />)}
                    </div>
                    <div className="recharge_ai_pay_box">
                        {
                            status !== 1 ? <>
                                <div className="recharge_ai_pay_qrcode" style={{ backgroundImage: `url("${qrCode}")`, backgroundSize: '100% 100%' }}>
                                    {status === 2 && <div className="res_mask" onClick={() => {
                                        getQRCode(select)
                                    }}>
                                        <i className="iconfont icon-zhongxin" style={{ fontSize: '12px' }}></i>
                                        <div style={{ marginTop: '6px' }}>点击刷新</div>
                                    </div>}
                                </div>
                                <div className="recharge_ai_pay_message">
                                    <div style={{ margin: '8px 0 11px 0' }}>
                                        <span style={{ marginBottom: '2px' }}>实际付款：</span>
                                        <span style={{
                                            color: '#EF3964',
                                            fontWeight: '500'
                                        }}>
                                            <span style={{ marginBottom: '1px' }}>￥</span>
                                            <span style={{ fontSize: '24px' }}>{price}</span>
                                        </span>
                                    </div>
                                    <div style={{
                                        marginBottom: '10px',
                                        lineHeight: '20px',
                                        display: 'flex',
                                        alignItems: 'center',
                                    }}>
                                        <span>使用</span>
                                        <div className="pay_icon wechat"></div>
                                        <span>微信</span>
                                        <span>/</span>
                                        <div className="pay_icon alipay"></div>
                                        <span>支付宝扫码支付</span>
                                    </div>
                                    <div style={{
                                        lineHeight: '20px',
                                    }}>
                                        支付即视为你同意
                                        {/* todo 颜色 字重 */}
                                        <span style={{ color: '#0057ff', cursor: 'pointer' }} onClick={() => { window.open("https://818ps.com/page/70") }}> 相关协议 </span>
                                        条例
                                    </div>
                                </div></> :
                                <div className="recharge_ai_pay_success">
                                    <div className="success_icon">
                                        <i className="iconfont icon-duigou"></i>
                                    </div>
                                    <div>充值成功</div>
                                </div>
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}
export default RechargeAiPopup